package cn.kooki.app.duobao.ui.Activity.User;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;

import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;


import com.baidu.autoupdatesdk.BDAutoUpdateSDK;
import com.baidu.autoupdatesdk.UICheckUpdateCallback;
import com.bumptech.glide.Glide;

import com.liulishuo.filedownloader.BaseDownloadTask;

import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;

import com.qihoo.appstore.updatelib.UpdateManager;
import com.umeng.analytics.MobclickAgent;
import com.umeng.update.UmengUpdateAgent;
import com.umeng.update.UmengUpdateListener;
import com.umeng.update.UpdateResponse;
import com.umeng.update.UpdateStatus;

import java.io.File;

import java.lang.ref.WeakReference;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.jpush.android.api.JPushInterface;
import cn.kooki.app.duobao.BuildConfig;
import cn.kooki.app.duobao.R;
import cn.kooki.app.duobao.base.BaseNavActivity;
import cn.kooki.app.duobao.core.MainFactory;
import cn.kooki.app.duobao.data.Bean.Index.NoticeItem;
import cn.kooki.app.duobao.data.Bean.base.BaseResponse;
import cn.kooki.app.duobao.data.Bean.base.CheckResponse;
import cn.kooki.app.duobao.data.bus.LoginChangeEvent;
import cn.kooki.app.duobao.data.constant.Constants;
import cn.kooki.app.duobao.ui.Activity.Comm.AboutActivity;
import cn.kooki.app.duobao.ui.Activity.Comm.WebViewActivity;
import cn.kooki.app.duobao.util.FileUtils;
import cn.kooki.app.duobao.util.PackageUtils;
import cn.kooki.app.duobao.util.SharePreferencesUtils;
import cn.kooki.app.duobao.util.StringUtils;
import cn.kooki.app.duobao.util.UpdateUtils;
import cn.kooki.app.duobao.util.helper.ProgressHelper;
import cn.kooki.app.duobao.util.listener.ProgressListener;
import cn.kooki.app.duobao.util.listener.impl.UIProgressListener;
import de.greenrobot.event.EventBus;
import retrofit.RetrofitError;

/**
 * Created by xiong on 2015/12/13.
 */
public class SettingActivity extends BaseNavActivity implements View.OnClickListener {

    @Bind(R.id.qa)
    RelativeLayout qa;
    @Bind(R.id.version)
    TextView version;
    @Bind(R.id.checkUpdate)
    RelativeLayout checkUpdate;
    @Bind(R.id.about_text)
    TextView aboutText;
    @Bind(R.id.about_layout)
    RelativeLayout aboutlayout;
    @Bind(R.id.feedback)
    RelativeLayout feedback;
    @Bind(R.id.cache)
    TextView cache;
    @Bind(R.id.clearCache)
    RelativeLayout clearCache;
    @Bind(R.id.logout)
    RelativeLayout logout;
    @Bind(R.id.logoutWrapper)
    LinearLayout logoutWrapper;

    @Override
    public void setLayoutContainerView() {
        setContainerView(R.layout.activity_settings);
        ButterKnife.bind(this);
    }


    @Override
    protected void afterView() {
        logout.setOnClickListener(this);
        aboutlayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intent(AboutActivity.class);

            }
        });
        topTextCenter.setText(R.string.title_activity_settings);
        topTextCenter.setVisibility(View.VISIBLE);
        String aboutstring = getString(R.string.settings_about);
        String aboutparse = String.format(aboutstring, getString(R.string.app_name));
        aboutText.setText(aboutparse);
        String appVersionName = PackageUtils.getAppVersionName(this);
        version.setText("Ver" + appVersionName + "");
        qa.setOnClickListener(this);
        clearCache.setOnClickListener(this);
        checkUpdate.setOnClickListener(this);

        countSize();
        FileUtils.makeDirs(Constants.APP_DOWNLOAD_PATH.toString());
    }

    private CountHandler handler = new CountHandler(this);

    private void countSize() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                File path = Glide.getPhotoCacheDir(SettingActivity.this);
                long dirSize = FileUtils.getDirSize(path);
                String fileMBSize = FileUtils.getFileMBSize(dirSize);
                Message message = Message.obtain();
                message.obj = fileMBSize;
                message.what = 1;
                handler.sendMessage(message);
            }
        }).start();

    }

    private static class CountHandler extends Handler {
        private static final long NOTICE_CHANGE_TIME = 5000;
        private final WeakReference<SettingActivity> mActivity;

        public CountHandler(SettingActivity activity) {
            mActivity = new WeakReference<SettingActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {

            if (mActivity.get() == null) {
                return;
            }
            if (msg.what == 1) {
                String size = (String) msg.obj;
                mActivity.get().cache.setText(size);
            }
        }
    }

    @Override
    public void onClick(View v) {
        if (v == logout) {
            SharePreferencesUtils.putBoolean(this, SharePreferencesUtils.ISLOGIN, false);
            LoginChangeEvent loginChangeEvent = new LoginChangeEvent();
            loginChangeEvent.islogin = false;
            MobclickAgent.onProfileSignOff();
            SharePreferencesUtils.clearUserinfo(this);
            JPushInterface.setAlias(getApplicationContext(), "", null);
            EventBus.getDefault().post(loginChangeEvent);
            finish();
        }
        if (v == aboutlayout){
        }

        if (v == qa) {
            intent(WebViewActivity.class, "type", WebViewActivity.QUESTION_TYPE);
        }
        if (v == clearCache) {
            new AlertDialog.Builder(this).
                    setMessage("确定要清空缓存么？").setPositiveButton("取消", null).
                    setNegativeButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            cleardisk();
                        }
                    }).show();
        }
        if (v == checkUpdate) {

            if (Constants.AUTO_TYPE_360.equals(BuildConfig.AUTO_TYPE)) {
                UpdateManager.checkUpdate(this,false);

            }else if (Constants.AUTO_TYPE_BAIDU.equals(BuildConfig.AUTO_TYPE)){
                BDAutoUpdateSDK.uiUpdateAction(this, new UICheckUpdateCallback() {
                    @Override
                    public void onCheckComplete() {

                    }
                });
            }else {
                UmengUpdateAgent.setUpdateAutoPopup(false);
                UmengUpdateAgent.setUpdateListener(new UmengUpdateListener() {
                    @Override
                    public void onUpdateReturned(int updateStatus, UpdateResponse updateResponse) {
                        switch (updateStatus){
                            case UpdateStatus.Yes: // has update
                                UmengUpdateAgent.showUpdateDialog(SettingActivity.this, updateResponse);
                                break;
                            case UpdateStatus.No:
                                showToastMessage("已是最新版本");
                                break;
                        }
                    }
                });
                UmengUpdateAgent.forceUpdate(this);
            }
        }
    }

    /**
     * 清理缓存
     */
    private void cleardisk() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Glide.get(SettingActivity.this).clearDiskCache();
                countSize();
            }
        }).start();
    }

}
